from rest_framework.permissions import IsAuthenticated
from dvadmin.utils.filters import DataLevelPermissionsFilter
from iot.models import Cabinet
from dvadmin.utils.serializers import CustomModelSerializer, serializers
from dvadmin.utils.viewset import CustomModelViewSet


class CabinetModelSerializer(CustomModelSerializer):
    dept_name = serializers.SerializerMethodField()

    def save(self, **kwargs):
        self.validated_data['dept_belong_id'] = self.validated_data['dept'].id
        return super().save(**kwargs)

    def get_dept_name(self, instance: Cabinet):
        return instance.dept.name

    class Meta:
        model = Cabinet
        fields = '__all__'


class CabinetModelViewSet(CustomModelViewSet):
    queryset = Cabinet.objects.all()
    serializer_class = CabinetModelSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DataLevelPermissionsFilter]
